package com.zzyl.nursing.service.impl;

import java.util.List;
import java.util.Set;

import cn.hutool.core.bean.BeanUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.dto.NursingPlanDto;
import com.zzyl.nursing.dto.NursingProjectPlanDto;
import com.zzyl.nursing.mapper.NursingProjectPlanMapper;
import com.zzyl.nursing.vo.NursingPlanVo;
import com.zzyl.nursing.vo.NursingProjectPlanVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingPlanMapper;
import com.zzyl.nursing.domain.NursingPlan;
import com.zzyl.nursing.service.INursingPlanService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 护理计划Service业务层处理
 *
 * @author dyc
 * @date 2025-07-05
 */
@Transactional
@Slf4j
@Service
public class NursingPlanServiceImpl implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;


    public final String CACHE_KEY_NURSING_PLAN = "nursing:plan:";
    public final String CACHE_KEY_NURSING_PLAN_ALL = "nursing:plan:all";

    /**
     * 查询护理计划关联的护理项目
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Integer id) {
        //查询缓存
        NursingPlanVo nursingPlanCache = (NursingPlanVo) redisTemplate.opsForValue().get(CACHE_KEY_NURSING_PLAN + id);
        if (nursingPlanCache != null) {
            return nursingPlanCache;
        }
        //查询护理计划
        NursingPlan nursingPlan = nursingPlanMapper.selectNursingPlanById(id);
        NursingPlanVo nursingPlanVo = new NursingPlanVo();
        BeanUtils.copyProperties(nursingPlan, nursingPlanVo);

        //根据护理计划ID查询护理项目的关系
        List<NursingProjectPlanVo> list = nursingProjectPlanMapper.selectByPlanId(id);
        nursingPlanVo.setProjectPlans(list);

        //添加缓存
        redisTemplate.opsForValue().set(CACHE_KEY_NURSING_PLAN + id, nursingPlanVo);
        return nursingPlanVo;
    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param dto 护理计划
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNursingPlan(NursingPlanDto dto) {
        try {
            // 校验护理项目是否为空
            if (dto.getProjectPlans() == null || dto.getProjectPlans().isEmpty()) {
                throw new BaseException("护理项目不能为空");
            }
            for (NursingProjectPlanDto projectPlan : dto.getProjectPlans()) {
                if (projectPlan.getProjectId() == null || projectPlan.getProjectId().isEmpty()) {
                    throw new BaseException("护理项目不能为空");
                }
            }

            //保存护理计划
            //属性拷贝
            //NursingPlan nursingPlan = new NursingPlan();
            //BeanUtils.copyProperties(dto, nursingPlan);
            NursingPlan nursingPlan = BeanUtil.toBean(dto, NursingPlan.class);
            nursingPlan.setCreateTime(DateUtils.getNowDate());
            int flag = nursingPlanMapper.insertNursingPlan(nursingPlan);
            //如果保存护理计划成功
            if (flag > 0) {
                // 即使count为0也应该删除缓存，因为护理计划本身已创建成功
                int count = nursingProjectPlanMapper.batchInsert(dto.getProjectPlans(), nursingPlan.getId());
                deleteCache(); // 删除缓存
                return count == 0 ? 0 : 1;
            }
            return flag;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    private void deleteCache() {
        // 使用keys方法获取所有匹配的键，然后批量删除
        Set<Object> keys = redisTemplate.keys(CACHE_KEY_NURSING_PLAN + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }


    /**
     * 修改护理计划
     *
     * @param nursingPlanDto 护理计划
     * @return 结果
     */
    @Override
    public int updateNursingPlan(NursingPlanDto nursingPlanDto) {
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
        //判断nursingPlanDto是否为空,如果不为空,则先删除全部护理计划,再批量保存
        //1.不为空
        if (nursingPlanDto.getProjectPlans() != null && !nursingPlanDto.getProjectPlans().isEmpty()) {
            //删除数据库的全部护理计划
            nursingProjectPlanMapper.deleteByPlanId(nursingPlan.getId());
            //批量保存护理项目计划关系
            nursingProjectPlanMapper.batchInsert(nursingPlanDto.getProjectPlans(), nursingPlan.getId());
        }
        //2.为空
        int result = nursingPlanMapper.updateNursingPlan(nursingPlan);
        //先更新数据库再删除缓存
        if (result > 0) {
            log.info("更新了护理计划,删除缓存");
            deleteCache(); // 更新后也删除缓存
        }
        return result;
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanByIds(Integer[] ids) {
        nursingProjectPlanMapper.deleteByPlanIds(ids);
        return nursingPlanMapper.deleteNursingPlanByIds(ids);
    }

    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteNursingPlanById(Integer id) {
        try {
            //删除护理计划与护理项目的关系
            nursingProjectPlanMapper.deleteByPlanId(id);
            //删除护理计划
            int flag = nursingPlanMapper.deleteNursingPlanById(id);
            if (flag > 0) {
                deleteCache(); // 删除缓存
            }
            return flag;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询所有护理计划
     *
     * @return
     */
    @Override
    public List<NursingPlan> nursingPlanAll() {
        //从缓存中获取
        List<NursingPlan> list = (List<NursingPlan>) redisTemplate.opsForValue().get(CACHE_KEY_NURSING_PLAN_ALL);
        if (list != null) {
            log.info("从缓存中获取了护理计划");
            return list;
        }
        //缓存中没有.从数据库中获取
        List<NursingPlan> nursingPlanlist = nursingPlanMapper.listAll();
        redisTemplate.opsForValue().set(CACHE_KEY_NURSING_PLAN_ALL, nursingPlanlist);
        return nursingPlanlist;
    }
}
